package com.beagle.njddapp.ui.activity.owner;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.amap.api.services.core.PoiItem;
import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.bean.ZdBean;
import com.beagle.njddapp.bean.owner.DIrverOrderBean;
import com.beagle.njddapp.bean.owner.DirverBean;
import com.beagle.njddapp.bean.owner.NjBean;
import com.beagle.njddapp.core.LocationManager;
import com.beagle.njddapp.ui.activity.ChooseAeraActivity;
import com.beagle.njddapp.ui.presenter.AddDirverPresenter;
import com.beagle.njddapp.ui.view.AddDirverView;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.weight.dialog.NjListDIalog;
import com.beagle.njddapp.weight.dialog.ZdDIalog;
import com.blankj.utilcode.util.ToastUtils;
import com.lljjcoder.citypickerview.widget.CityPicker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author hxx
 * @date 2021-03-02 22:31
 * 添加农机驾驶员
 */
public class AddDirverActivity extends BaseMvpActivity<AddDirverView, AddDirverPresenter> implements AddDirverView, NjListDIalog.onNjDialogItemClickLisenter, ZdDIalog.ZdDialogItemClickLisenter {


    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.common_container)
    RelativeLayout container;
    @BindView(R.id.common_tv_right)
    TextView tvRight;
    @BindView(R.id.tv_choose_device)
    TextView tvDevice;
    @BindView(R.id.tv_choose_type)
    TextView tvType;
    @BindView(R.id.tv_choose_time)
    TextView tvTime;
    @BindView(R.id.tv_choose_time_end)
    TextView tvTimeEnd;
    @BindView(R.id.ed_address)
    EditText edAdress;
    @BindView(R.id.ed_money)
    EditText edMoney;
    private DirverBean dirverBean;
    private DIrverOrderBean dIrverOrderBean;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.view_address)
    View viewAddress;
    private int id;
    private NjListDIalog njListDIalog;
    private List<NjBean> njBeanList;
    private ZdDIalog zdDIalog;
    private String type;
    private PoiItem currentPos;
    private boolean isnow; //是否选择当前定位位置

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_dirver;
    }

    @Override
    public void init() {
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        dirverBean = new DirverBean();
        njBeanList = new ArrayList<>();
        tvTitle.setText("添加作业订单");
        dIrverOrderBean = (DIrverOrderBean) getIntent().getSerializableExtra("data");
        if (dIrverOrderBean != null) {
            id = dIrverOrderBean.getMeshId();
            type = dIrverOrderBean.getWorkType();
            tvRight.setText("完成");
            tvTitle.setText("作业订单修改");
            tvDevice.setText(dIrverOrderBean.getMeshNum());
            tvType.setText(dIrverOrderBean.getWorkTypeName());
            type = dIrverOrderBean.getWorkType();
            tvTime.setText(dIrverOrderBean.getBeginDate());
            tvTimeEnd.setText(dIrverOrderBean.getEndDate());
            tvAddress.setText(dIrverOrderBean.getWorkAddress());
            edMoney.setText(dIrverOrderBean.getWorkPrice());
            tvNext.setVisibility(View.GONE);
        }

        presenter.getDeviceListRun(100, 1);
    }

    @Override
    public AddDirverView getMvpView() {
        return this;
    }

    @Override
    public AddDirverPresenter createPresenter() {
        return new AddDirverPresenter();
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(message);
    }

    @OnClick({R.id.common_back_iv, R.id.common_tv_right, R.id.tv_next, R.id.tv_choose_device, R.id.tv_choose_type, R.id.tv_choose_time, R.id.tv_choose_time_end,R.id.tv_address})
    public void onCLick(View view) {
        switch (view.getId()) {
            case R.id.common_back_iv:
                onBackPressed();
                break;
            case R.id.tv_choose_device:
                if (njBeanList == null || njBeanList.size() == 0) {
                    ToastUtils.showShort("请先添加农机");
                    return;
                }
                if (njListDIalog == null) {
                    njListDIalog = new NjListDIalog(this);
                    njListDIalog.setOnNjDialogItemClickLisenter(this);
                }
                njListDIalog.show();
                njListDIalog.setNjBeanList(njBeanList);
                break;
            case R.id.tv_choose_type:
                presenter.queryDictList("4", "");
                break;
            case R.id.tv_choose_time:
                chooseTime(1);
                break;
            case R.id.tv_choose_time_end:
                chooseTime(2);
                break;
            case R.id.tv_address:
                startActivityForResult(new Intent(this, ChooseAeraActivity.class),155);
//                cityPicker();
                break;
            case R.id.tv_next:
                if (TextUtils.isEmpty(tvDevice.getText().toString()) || TextUtils.isEmpty(tvType.getText().toString()) ||
                        TextUtils.isEmpty(tvTime.getText().toString()) || TextUtils.isEmpty(tvAddress.getText().toString())
                        || TextUtils.isEmpty(edMoney.getText().toString()) || TextUtils.isEmpty(tvTimeEnd.getText().toString())) {
                    ToastUtils.showShort("请填写完整信息");
                } else {
                    dirverBean.setBeginDate(tvTime.getText().toString());
                    dirverBean.setEndDate(tvTimeEnd.getText().toString());
                    dirverBean.setMeshId(id + "");
                    dirverBean.setWorkAddress(tvAddress.getText().toString()+edAdress.getText().toString());
                    dirverBean.setWorkPrice(edMoney.getText().toString());
                    dirverBean.setMeshNum(tvDevice.getText().toString());
                    dirverBean.setWorkType(type);
                    if (currentPos!=null){
                        dirverBean.setPlantLat(currentPos.getLatLonPoint().getLatitude()+"");
                        dirverBean.setPlantLng(currentPos.getLatLonPoint().getLongitude()+"");
                    }else if (TextUtils.isEmpty(dirverBean.getPlantLat())){
                        dirverBean.setPlantLat(LocationManager.getInstance().location.getLatitude()+"");
                        dirverBean.setPlantLng(LocationManager.getInstance().location.getLongitude()+"");
                    }
                    presenter.addFindDriverOrder(dirverBean);
                }
                break;
            case R.id.common_tv_right:
                if (TextUtils.isEmpty(tvDevice.getText().toString()) || TextUtils.isEmpty(tvType.getText().toString()) ||
                        TextUtils.isEmpty(tvTime.getText().toString()) || TextUtils.isEmpty(tvAddress.getText().toString())
                        || TextUtils.isEmpty(edMoney.getText().toString()) || TextUtils.isEmpty(tvTimeEnd.getText().toString())) {
                    ToastUtils.showShort("请填写完整信息");
                } else {
                    dIrverOrderBean.setBeginDate(tvTime.getText().toString());
                    dIrverOrderBean.setEndDate(tvTimeEnd.getText().toString());
                    dIrverOrderBean.setMeshId(id);
                    dIrverOrderBean.setWorkAddress(tvAddress.getText().toString()+edAdress.getText().toString());
                    dIrverOrderBean.setWorkPrice(edMoney.getText().toString());
                    dIrverOrderBean.setMeshNum(tvDevice.getText().toString());
                    if (!TextUtils.isEmpty(type)) {
                        dIrverOrderBean.setWorkType(type);
                    }
                    presenter.updateFindDriverOrder(dIrverOrderBean);
                }
                break;
        }
    }

    private void chooseTime(int type) {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                String monthStr;
                if (month < 9) {
                    monthStr = "0" + (month + 1);
                } else {
                    monthStr = (month + 1) + "";
                }

                if (type == 1) {
                    tvTime.setText(year + "-" + monthStr + "-" + dayOfMonth);
                } else {
                    if (TextUtils.isEmpty(tvTime.getText().toString())) {
                        ToastUtils.showShort("请先选择开始日期");
                        return;
                    }
                    String time = year + "-" + monthStr + "-" + dayOfMonth;
                    tvTimeEnd.setText(time);
//                    long start = getTime(tvTime.getText().toString());
//                    long end = getTime(time);
//                    if (end > start) {
//                        tvTimeEnd.setText(time);
//                    } else {
//                        ToastUtils.showShort("结束日期不能小于开始日期");
//                    }


                }
            }
        },

                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMinDate(new Date().getTime());
        datePickerDialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==144&&data!=null){
            PoiItem poiItem=data.getParcelableExtra("pos");
            if (poiItem!=null){
                currentPos=poiItem;
                tvAddress.setText(currentPos.getProvinceName()+currentPos.getCityName()+currentPos.getAdName()+currentPos.getTitle()+currentPos.getSnippet());
                edAdress.setVisibility(View.VISIBLE);
                viewAddress.setVisibility(View.VISIBLE);
                edAdress.setText("");
            }
        }else   if (resultCode==244&&data!=null){
            isnow=data.getBooleanExtra("loc",false);
            if (isnow){
                tvAddress.setText(LocationManager.getInstance().getLocation());
                edAdress.setVisibility(View.VISIBLE);
                viewAddress.setVisibility(View.VISIBLE);
                edAdress.setText("");
            }
        }
    }

    public void cityPicker(){
        CityPicker cityPicker = new CityPicker.Builder(this)
                .textSize(14)
                .title("地址选择")
                .titleBackgroundColor("#FFFFFF")
                .confirTextColor("#696969")
                .cancelTextColor("#696969")
                .province(LocationManager.getInstance().getProvince())
                .city(LocationManager.getInstance().getCity())
                .district(LocationManager.getInstance().getDistrict())
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                String province = citySelected[0];
                //城市
                String city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //邮编
                String code = citySelected[3];
                //为TextView赋值
                tvAddress.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
                edAdress.setVisibility(View.VISIBLE);
                viewAddress.setVisibility(View.VISIBLE);
                edAdress.setText("");
            }
        });

    }

    @Override
    public void addSuccess() {
        setResult(306);
        finish();
    }

    public long getTime(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        long startDay = 0;

        try {
            Date dateStart = format.parse(time);
            startDay = (int) (dateStart.getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return startDay;
    }

    @Override
    public void showRunNj(List<NjBean> results) {
        njBeanList.addAll(results);
    }

    @Override
    public void updateSuccess() {
        finish();
    }

    @Override
    public void showZd(List<ZdBean> items) {
        if (zdDIalog == null) {
            zdDIalog = new ZdDIalog(this);
            zdDIalog.setZdDialogItemClickLisenter(this);
        }
        zdDIalog.show();
        zdDIalog.setZdBeanList(items);
    }

    @Override
    public void onItemClick(NjBean njBean) {
        tvDevice.setText(njBean.getMeshNum());
        id = njBean.getMeshId();
    }

    @Override
    public void onZdItemClick(ZdBean zdBean) {
        tvType.setText(zdBean.getName());
        type = zdBean.getValue();
    }
}
